﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;

namespace WPFSample.PrintaBunchaButtonsSample
{
    class PrintaBunchaButtons : Window
    {
        public PrintaBunchaButtons()
        {
            this.Title = "Print a Bunch of Buttons";
            this.SizeToContent = SizeToContent.WidthAndHeight;
            this.ResizeMode = ResizeMode.CanMinimize;

            Button btn = new Button()
            {
                FontSize = 24,
                Content = "Print...",
                Padding = new Thickness(12),
                Margin = new Thickness(96)
            };
            btn.Click += this.PrintOnClick;
            this.Content = btn;
        }

        private void PrintOnClick(object sender, RoutedEventArgs e)
        {
            PrintDialog dlg = new PrintDialog();
            if (dlg.ShowDialog().GetValueOrDefault())
            {
                Grid grid = new Grid();
                for (int i = 0; i < 5; i++)
                {
                    ColumnDefinition coldef = new ColumnDefinition();
                    coldef.Width = GridLength.Auto;
                    grid.ColumnDefinitions.Add(coldef);

                    RowDefinition rowdef = new RowDefinition();
                    rowdef.Height = GridLength.Auto;
                    grid.RowDefinitions.Add(rowdef);
                }

                grid.Background = new LinearGradientBrush(Colors.Gray, Colors.White, new Point(0, 0), new Point(1, 1));

                Random rand = new Random();
                for (int i = 0; i < 25; i++)
                {
                    Button btn = new Button()
                    {
                        FontSize = 12 + rand.Next(8),
                        Content = "Button No." + (i + 1),
                        HorizontalAlignment = HorizontalAlignment.Center,
                        VerticalAlignment = VerticalAlignment.Center,
                        Margin = new Thickness(6)
                    };
                    grid.Children.Add(btn);
                    Grid.SetRow(btn, i % 5);
                    Grid.SetColumn(btn, i / 5);
                }

                grid.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity));

                Size sizeGrid = grid.DesiredSize;
                Point ptGrid = new Point((dlg.PrintableAreaWidth - sizeGrid.Width) / 2, (dlg.PrintableAreaHeight - sizeGrid.Height) / 2);
                grid.Arrange(new Rect(ptGrid, sizeGrid));

                dlg.PrintVisual(grid, this.Title);
            }
        }
    }
}
